package org.cheetahworkflow.designer.part;

import java.beans.PropertyChangeEvent;
import java.util.List;

import org.cheetahworkflow.designer.model.Arrow;
import org.cheetahworkflow.designer.model.Chart;
import org.cheetahworkflow.designer.model.ConditionArrow;
import org.cheetahworkflow.designer.model.RapidView;
import org.cheetahworkflow.designer.model.SwitchNode;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.jface.dialogs.MessageDialog;

public class ConditionArrowPart extends ArrowPart {

	@Override
	protected IFigure createFigure() {
		PolylineConnection figure = (PolylineConnection) super.createFigure();
		if (((ConditionArrow) getModel()).isDefault()) {
			figure.setForegroundColor(ColorConstants.red);
		}
		return figure;
	}
	
	@Override
	public void resetLineStyle(PropertyChangeEvent event) {
		boolean isSetDefault = (Boolean) event.getNewValue();
		
		if (isSetDefault) {
			ConditionArrow arrow = (ConditionArrow) event.getSource();
			SwitchNode node = (SwitchNode) arrow.getSource();
			List<Arrow> list = node.getOutgoingArrow();
			for(Arrow bro: list) {
				// if there is another bro arrow is default arrow, refuse the request 
				if (bro != arrow && ((ConditionArrow) bro).isDefault()) {
					arrow.setDefault(false);
					MessageDialog.openInformation(getViewer().getControl().getShell(), "Error", "One switch node should have no more than 1 default arrow.");
					return;
				}
			}
			
			PolylineConnection figure = (PolylineConnection) getFigure();
			figure.setForegroundColor(ColorConstants.red);
		}
	}
	
	@Override
	public void eraseTargetFeedback(Request request) {
		super.eraseTargetFeedback(request);
		ConditionArrow model = (ConditionArrow) getModel();
		Chart chart = model.getChart();
		chart.removeRapidView();
	}
	
	@Override
	public void showTargetFeedback(Request request) {
		super.showTargetFeedback(request);
		if (request.getType() == RequestConstants.REQ_SELECTION_HOVER) {
			ConditionArrow model = (ConditionArrow) getModel();
			Chart chart = model.getChart();
			RapidView rapidView = model.getRapidView(((PolylineConnection) getFigure()).getStart());
			chart.setRapidView(rapidView);
		}
	}
}
